import axios from 'axios'

axios.defaults.withCredentials = true;// 允许跨域携带cookie


// import { Message } from 'element-ui'
import {message} from './resetMessage';
import store from '@/store'
import {getToken} from '@/utils/auth'
import '@/styles/index.scss' // global css
import Qs from 'qs'
import CryptoJS from '@/utils/crypto'


// let serverUrl = "https://admin.zleniao.com/CM-API/";
// let serverUrl = "http://hailiang.58vip.cn/CM-API/";
let serverUrl = "https://education.vastdata.com.cn/CM-API/";
// let serverUrl = "https://hailiang.58vip.cn/CM-API/";

// let serverUrl = "/CM-API/";
let baseURL = process.env.NODE_ENV == 'development' ? '/CM-API/' : serverUrl

// create an axios instance
const service = axios.create({
    baseURL: baseURL, // api 的 base_url
    timeout: 500000, // request timeout
    headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Authorization": "Bearer " + getToken()
    },
    transformRequest: [function (data) {      //在请求之前对data传参进行格式转换
        // data = data instanceof Long ? data : JSONBIG(data)
        data = data instanceof FormData ? data : Qs.stringify(data)
        return data
    }],
})

// request interceptor
service.interceptors.request.use(
    config => {

        // springCloud版本---附加模块名称---方便路由解析
        // if( config.modules){
        //     config.baseURL += config.modules +"/" ;
        // }

        // Do something before request is sent
        if (store.getters.token && store.getters.token != undefined) {

            //【springCloud版本】
            config.headers['Authorization'] = "Bearer " + getToken()

            //【springboot版本】
            config.headers['accesstoken'] = getToken();
        } else {
            delete config.headers['Authorization'];
        }
        return config
    },
    error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    //response => response,
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     */
    response => {
        const res = response.data

        if (res.code == 500) {
            if (response.config.url.indexOf("getUserInfo") > -1) {
                message({
                    message: "登录会话过期，请重新登录",
                    type: 'error',
                    duration: 5 * 1000,
                    customClass:'theme-message'
                })
                store.dispatch('user/logOut');
                return Promise.reject('error')
            } else {

                message({
                    title: '失败',
                    message: res.msg,
                    type: 'error',
                    duration: 5 * 1000,
                    customClass:'theme-message'
                })
                return Promise.reject(res.msg)
            }

        } else if (res.code == 401) {

            if (response.config.url.indexOf("getUserInfo") > -1) {
                message({
                    message: "登录会话过期，请重新登录",
                    type: 'error',
                    duration: 3 * 1000,
                    customClass:'theme-message'
                })
                store.dispatch('user/logOut');
                return Promise.reject('error')
            } else {

                message({
                    message: '会话过期，请重新登录',
                    type: 'error',
                    duration: 3 * 1000,
                    customClass:'theme-message'
                })

                store.dispatch('user/logOut').then(() => {
                    location.reload()
                })
                return;
            }

            // return Promise.reject('error')

        } else if (res.code == 0) {
            if (res.data != null) {
                // 解密
                const decrypted = CryptoJS.Decrypt(res.data);
                console.log(decrypted, 'Decrypted Data');
                const parsed = JSON.parse(decrypted);
                console.log(parsed, 'JSON Data');
                response.data.data = parsed;
                console.log(response.data, 'response.data');
                return response.data;
            } else {
                return response.data;
            }

        } else {//模拟数据

            message({
                message: res.message,
                type: 'error',
                duration: 5 * 1000,
                customClass:'theme-message'
            })
            return Promise.reject(res.message)

        }
    },
    error => {


        let errorResp = error.response;


        if (errorResp.status === 404) {
            message({
                message: errorResp.data,
                type: 'error',
                duration: 3 * 1000
            })
            return Promise.reject(error)
        } else {

            message({
                message: errorResp.data,
                type: 'error',
                duration: 5 * 1000
            })
            return;

        }
    }

)

export default service